/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controlador;

import Modelo.Imagen;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
 *
 * @author Damian
 */
public class ControlImagen extends Conexion {

    public ControlImagen() {
    }

    public void guardarImagen(String ruta, String nombre) throws SQLException, FileNotFoundException {
        String insert = "INSERT INTO imagen(img_imagen,img_nombre) values(?,?)";
        FileInputStream fis = null;
        PreparedStatement ps = null;
        Connection cn = conectar();
        cn.setAutoCommit(false);
        File file = new File(ruta);
        fis = new FileInputStream(file);
        ps = cn.prepareStatement(insert);
        ps.setBinaryStream(1, fis, (int) file.length());
        ps.setString(2, nombre);
        ps.executeUpdate();
        cn.commit();

        try {
            ps.close();
            fis.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public ArrayList<Imagen> getImagenes() throws SQLException {
        ArrayList<Imagen> lista = new ArrayList();
        Connection cn = conectar();
        PreparedStatement ps = cn.prepareStatement("SELECT img_codigo,img_imagen,img_nombre FROM imagen");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Imagen imagen = new Imagen();
            Blob blob = rs.getBlob("img_imagen");
            String nombre = rs.getObject("img_nombre").toString();
            String cod=rs.getString("img_codigo");
            byte[] data = blob.getBytes(1, (int) blob.length());
            BufferedImage img = null;
            try {
                img = ImageIO.read(new ByteArrayInputStream(data));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            imagen.setImagen(img);
            imagen.setNombre(nombre);
            imagen.setCod(cod);
            lista.add(imagen);
        }
        rs.close();

        return lista;
    }

    public Image redimensionar(Image img,int w, int h) {
        ImageIcon fot = new ImageIcon(img);
        ImageIcon icono = new ImageIcon(fot.getImage().getScaledInstance(
                w, h, Image.SCALE_DEFAULT));
        return icono.getImage();
    }
}
